import {
	httpsUrl,
	tokenKey
} from '@/config';
import store from '@/store';

class base {
	async request(url, method, data = {}, option = {}, header = {}) {
		// 配置
		this._url = '';
		this._method = method || 'GET';
		this._data = data;
		this._option = Object.assign({
			noAuth: false, //不需要验证token
			noVerify: false, //不需要状态码验证
		}, option);
		this._header = header;
		try {
			// 请求前拦截
			await this._interceptBefore(url);
			// 请求
			const result = await this._request();
			// 请求后拦截
			const res = await this._interceptAfter(result);
			return res;
		} catch (err) {
			uni.showModal({
				content: err.message,
				showCancel: false
			})
		}
	}
	// 请求前拦截
	async _interceptBefore(url) {
		let {
			noUrl,
			noAuth
		} = this._option;
		// 路径处理
		this._url = noUrl ? url : httpsUrl + url;
		// header 处理
		let header = Object.assign({}, this._header);
		if (!noAuth) {
			let token = store.state.userInfo.accessToken;
			if (!token) await store.dispatch('userInfo/getToken');
			token = store.state.userInfo.accessToken;
			if (token) header[tokenKey] = token;
		}
		this._header = header;
	}
	// 请求后拦截
	_interceptAfter(res) {
		let {
			noVerify
		} = this._option;
		return new Promise((reslove, reject) => {
			if (noVerify) return reslove(res.data);
			switch (res.data.code) {
				case 0:
					reslove(res.data);
					break;
				case 4007:
					uni.setStorageSync('_TOKEN', JSON.stringify({}));
					store.dispatch('userInfo/getToken');
					// reject(new Error(res.data.msg || '系统错误'));
					reslove();
					break;
				default:
					reject(new Error(res.data.msg || '系统错误'));
					break;
			}
		})
	}
	// 请求
	_request() {
		return new Promise((reslove, reject) => {
			uni.request({
				url: this._url,
				method: this._method,
				header: this._header,
				data: this._data || {},
				
				success: (res) => reslove(res),
				fail: (msg) => {
					reject(new Error('请求失败'));
				}
			})
		});
	}
	async downloadFile(url,option={},header={}){
		// 配置
		this._url = '';
		this._option = Object.assign({
			noAuth: false, //不需要验证token
			noVerify: false, //不需要状态码验证
		}, option);
		this._header = header;
		try {
			// 请求前拦截
			await this._interceptBefore(url);
			// 请求
			const result = await this._downloadFile();
			return result;
		} catch (err) {
			uni.showModal({
				content: err.message,
				showCancel: false
			})
		}
	}
	_downloadFile(url, option = {}, header = {}){
		return new Promise((reslove, reject) => {
			uni.request({
				url: this._url,
				header: this._header,
				success: (res) => reslove(res),
				fail: (msg) => {
					reject(new Error('请求失败'));
				}
			})
		});
	}
	
	async uploadFile(url,data = {}, option = {}, header = {}) {
		// 配置
		this._url = '';
		this._data = data;
		this._option = Object.assign({
			noAuth: false, //不需要验证token
			noVerify: false, //不需要状态码验证
		}, option);
		this._header = header;
		try {
			// 请求前拦截
			await this._interceptBefore(url);
			// 请求
			const result = await this._uploadFile();
			// 请求后拦截
			const res = await this._interceptAfter(result);
			return res;
		} catch (err) {
			uni.showModal({
				content: err.message,
				showCancel: false
			})
		}
	}

	// 上传文件
	_uploadFile() {
		return new Promise((reslove, reject) => {
			let {filePath='',name='file',formData={}}=this._data;
			uni.uploadFile({
				url: this._url,
				header: this._header,
				filePath,
				name,
				formData,
				success: (res) => reslove(res),
				fail: (msg) => {
					reject(new Error('请求失败'));
				}
			})
		});
	}
}


const request = {};


['get', 'post', 'put', 'delete'].forEach((method) => {
	request[method] = async (api, data, opt, header) => {
		const baseRequest = new base();
		return baseRequest.request(api, method, data, opt, header)
	};
});

request['uploadFile'] = async (api, data, opt,  header) => {
	const baseRequest = new base();
	return baseRequest.uploadFile(api,  data, opt, header)
};

request['downloadFile'] = async (api, opt,  header) => {
	const baseRequest = new base();
	return baseRequest.downloadFile(api,  opt, header)
};


export default request;